package org.linlinjava.litemall.core.util;

import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.google.common.collect.Maps;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Stream;

public class CommonUtils {

    public static final String SPLIT_SYMBOL = ",";

    public static final String SPLIT_SYMBOL2 = ";";

    /**
     * lambda表示式去重
     *
     * @param keyExtractor
     * @param <T>
     * @return
     */
    public static <T> Predicate<T> distinctByKey(Function<? super T, Object> keyExtractor) {
        Map<Object, Boolean> seen = Maps.newConcurrentMap();
        return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
    }

    public static String join(String symbol, String... string) {
        Joiner joiner = Joiner.on(symbol);
        return joiner.join(string);
    }

    public static List<String> split(String parameter, String symbol) {
        Splitter splitter = Splitter.on(symbol);
        return splitter.splitToList(parameter);
    }

    public static BigDecimal plus(BigDecimal... numbers) {
        Stream<BigDecimal> bigDecimalStream = Stream.of(numbers);
        return bigDecimalStream.reduce(BigDecimal.ZERO, BigDecimal::add);
    }

    public static BigDecimal subtract(BigDecimal b1, BigDecimal b2) {
        return subtract(b1, b2, 2);
    }

    public static BigDecimal subtract(BigDecimal b1, BigDecimal b2, int scale) {
        return b1.subtract(b2).setScale(scale, BigDecimal.ROUND_HALF_UP);
    }

    public static BigDecimal mul(BigDecimal b1, BigDecimal b2, int scale) {
        return b1.multiply(b2).setScale(scale, BigDecimal.ROUND_HALF_UP);
    }

    public static String getPingbStr(String str, int starIndex) {
        if (str.length() >= starIndex) {
            String substring = str.substring(0, starIndex);
            str = substring + "***";
        }
        return str;
    }

}
